微信小程序组件的引入和调用的方法
时间 :
2022-10-25
编辑 :admin
看一下我的组件结构 components(被调用的组件) index(页面组件)请忽略调图片


module文件就是我所创的自定义组件,module.wxml文件代码为:
| 1 2 3 |
<view class="inner"> <Text>I am learning 微信小程序</Text></view> |
module.js文件代码为:
const app = getApp()
Component({
properties: {
// 这里定义了innerText属性,属性值可以在组件使用时指定
innerText: {
type: String,
// value: '',
}
},
data: {
// 这里是一些组件内部数据
someData: {}
},
methods: {
customMethod(){
console.log('hello world! I am learning 微信小程序')
}
}
})
现在我要在pages/index文件中使用该自定义组件,该怎么做呢?
1、在module.json文件中添加以下代码:
{
"component": true
}
2、在需要调用自定义组件的文件中,如pages/index文件需要调用自定义组件,那么则需要在pages/index/index.json文件中添加如下代码:
{
"usingComponents": {
"module": "../../components/module/module" // 组件名以及组件所在路径
}
}
3、然后就可以在module.wxml文件中使用该自定义组件了,
index.wxml文件代码如下:
<view>
<module id="module"></module>
</view>
此时调用自定义组件后,效果如下:


4、现在要调用自定义组件中的方法就可以这样做,为了方便,这里我使用的是点击按钮调用事件,因此index.wxml文件代码变为:
<view>
<button bindtap="showComponent">组件调用</button>
<module id="module"></module>
</view>
5、index.js文件部分代码为:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
const app = getApp()import { Resume } from '../../request/api'const request = new Resume()Page({ data: { }, onLoad: function () { // request.testInitial({ 'name':'123' }).then(res=>{ // console.log(res) // }) }, onReady: function () { // 页面初次渲染完成后,使用选择器选择组件实例节点,返回匹配到组件实例对象 this.module= this.selectComponent('#module') }, showComponent: function () { let module= this.module module.customMethod() // 调用自定义组件中的方法 }}) |
最后的结果:


